package com.edu.chat.web.covert;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.edu.chat.facade.model.dto.SceneInfoDTO;
import com.edu.chat.web.controller.vo.SceneVO;
import com.edu.chat.web.model.CsScene;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-31 23:11
 **/


public class SceneCovert {

	public static SceneInfoDTO convertSceneInfoDTO(CsScene scene) {
		SceneInfoDTO sceneInfoDTO = new SceneInfoDTO();
		sceneInfoDTO.setSceneId(String.valueOf(scene.getId()));
		sceneInfoDTO.setSceneName(scene.getSceneName());
		sceneInfoDTO.setSceneLogo(scene.getSceneLogo());
		sceneInfoDTO.setRobotId(String.valueOf(scene.getRobotId()));
		sceneInfoDTO.setLibraryIds(scene.getLibraryIds());
		sceneInfoDTO.setDescription(scene.getDescription());
		sceneInfoDTO.setStatus(scene.getStatus());
		sceneInfoDTO.setTenantId(scene.getTenantId());
		sceneInfoDTO.setSceneCode(scene.getSceneCode());

		Optional.ofNullable(scene.getSceneConfig()).ifPresent(config->{
			Map<String, Object> bean = JSONUtil.toBean(config, new TypeReference<>() {
			}, true);
			sceneInfoDTO.setSceneConfig(bean);
		});

		Optional.ofNullable(scene.getCreatedAt()).ifPresent(createdAt->{
			sceneInfoDTO.setCreatedAt(DateUtil.format(createdAt, "yyyy-MM-dd HH:mm:ss"));
		});

		//创建人
		Optional.ofNullable(scene.getCreatedBy()).ifPresent(sceneInfoDTO::setCreator);

		return sceneInfoDTO;
	}

	public static CsScene convertScene(SceneVO sceneVO) {
		if (sceneVO == null) return null;

		CsScene scene = new CsScene();
		scene.setId(sceneVO.getSceneId());  // 修正 VO 字段来源

		// 处理空集合情况
		List<String> libraryIds = sceneVO.getLibraryIds() != null ?
				sceneVO.getLibraryIds() : Collections.emptyList();
		scene.setLibraryIds(String.join(",", libraryIds));

		// 安全生成场景编码
		String idStr = String.format("%04d", sceneVO.getSceneId() != null ? sceneVO.getSceneId() : 0);
		scene.setSceneCode("SC_" + idStr.substring(0, Math.min(4, idStr.length())));

		// 简化 Optional 使用
		Optional.ofNullable(sceneVO.getSceneConfig())
				.map(JSONUtil::toJsonStr)
				.ifPresent(scene::setSceneConfig);

		scene.setSceneName(sceneVO.getSceneName());
		scene.setSceneLogo(sceneVO.getSceneLogo());
		scene.setRobotId(sceneVO.getRobotId());
		scene.setDescription(sceneVO.getDescription());
		scene.setStatus(sceneVO.getStatus());

		return scene;
	}

}
